package com.maggie.measure.micrometer.aspect;

import com.maggie.measure.micrometer.metric.RedisMetric;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Aspect
@SuppressWarnings("all")
@Component("redisApiAspect")
public class RedisApiAspect {

    public static Map incrMap = new HashMap<>();

    @Pointcut("execution(public * com.maggie.measure.micrometer.service.RedisOpsValService.*(..))")
    private void redisApi() {
    }

    @Around("redisApi()")
    public Object doProfiling(ProceedingJoinPoint point) throws Throwable {

        long initTime = System.currentTimeMillis();
        long sTime = initTime, eTime = initTime;


        MethodSignature methodSignature = null;
        Object proceed = null;
        try {
            methodSignature = (MethodSignature) point.getSignature();
        } finally {
            String met = methodSignature.getName(); // 拦截方法名称
            Object[] args = point.getArgs(); // 拦截的方法参数
            proceed = point.proceed();
            if ("get".equals(met)) {
                RedisMetric.atomicGetInteger.getAndIncrement();
            }
            if ("set".equals(met)) {
                RedisMetric.atomicSetInteger.getAndIncrement();
            }
            if (RedisMetric.param.get(met) != null) {
                Map<String, Object> metMap = RedisMetric.param.get(met);
                incrMap.put(met + "incr", Double.valueOf((Integer) metMap.getOrDefault(met + "incr", 0) + 1));
                int incr = (Integer) incrMap.getOrDefault(met + args[0] + "incr", 0) + 1;
                incrMap.put(met + args[0] + "incr", incr);
                if (args != null && args[0] instanceof String) {
                    metMap.put((String) args[0], incr);
                }
            } else {
                Map<String, Object> metMap = new HashMap<>();
                incrMap.put(met + "incr", Double.valueOf((Integer) metMap.getOrDefault(met + "incr", 0) + 1));
                int incr = (Integer) incrMap.getOrDefault(met + args[0] + "incr", 0) + 1;
                if (incrMap.get(met + args[0] + "incr") == null) {
                    incrMap.put(met + args[0] + "incr", incr);
                }
                if (args != null && args[0] instanceof String) {
                    metMap.put((String) args[0], incr);
                }
                RedisMetric.param.put(met, metMap);
            }
        }
        return proceed;
    }
}
